package com.lemon.smartsafety.rayeye;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.rayeye.adapter.BuildingListAdapter;
import com.lemon.smartsafety.rayeye.entity.Building;
import com.lemon.smartsafety.rayeye.entity.BuildingListVo;
import com.lemon.smartsafety.rayeye.util.Urls;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Cooliean on 16/4/15.
 */
public class BuildingListActivity extends SwipeBackActivity {

    @Bind(R.id.tv_tip)
    TextView                  tvTip;
    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView pullToRefreshRecyclerView;
    @Bind(R.id.multiStateView)
    MultiStateView            multiStateView;
    @Bind(R.id.float_button)
    FloatingActionButton      floatButton;

    private CompanyInfo mCompanyInfo = null;


    private BuildingListVo mBuildingListVo;


    private int pageSize    = 30;
    private int currentPage = 1;

    BuildingListAdapter mAdapter;
    List<Building> items = new ArrayList<>();

    private LinearLayoutManager mLayoutManager;


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COMPANY_INFO);
        }
    }


    @Override
    protected void initTitle() {
        setBarTitle("消防监督");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(BuildingListActivity.class);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_list_refresh;
    }

    @Override
    protected void initViews() {
        super.initViews();
        if (mCompanyInfo == null) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
            return;
        }

        initVar();
        pullToRefreshRecyclerView.beginRefreshing();
    }

    private void initVar() {

        multiStateView.setRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                pullToRefreshRecyclerView.beginRefreshing();
            }
        });
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mAdapter = new BuildingListAdapter(items, new RecyclerTClickListener<Building>() {
            @Override
            public void onItemClick(Building data, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(com.lemon.smartsafety.rayeye.entity.BundleKey.BUILDING, data);
                bundle.putSerializable(com.lemon.smartsafety.rayeye.entity.BundleKey.COMPANY_INFO, mCompanyInfo);
                UIHelper.showActivity(BuildingListActivity.this, bundle, FireAllListActivity.class);
            }
        });
        pullToRefreshRecyclerView.setLayoutManager(mLayoutManager);
        pullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        pullToRefreshRecyclerView.setAdapter(mAdapter);
        pullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getNetData();
            }
        });
        pullToRefreshRecyclerView.setOnPullDownToRefreshListener(new PullToRefreshRecyclerView.OnPullDownToRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData();
            }
        });

    }

    private void getNetData() {
        LemonRequestParams params = new LemonRequestParams();
        params.put("code", StringUtils.nullValue(this.mCompanyInfo.getCompany_code()));
        params.put("key", Urls.APP_FIRE_SUPERVISON_KEY);
        params.put("limit", pageSize);
        params.put("page", currentPage);
        OkHttpUtils.post()
                   .url(String.format(Urls.GET_BUILDING_LIST, mSharedPreferencesHelper.getRayEyeUrl()))
                   .tag(String.format(Urls.GET_BUILDING_LIST, mSharedPreferencesHelper.getRayEyeUrl()))
                   .params(params)
                   .build()
                   .execute(new Callback<BuildingListVo>() {
                       @Override
                       public void onBefore(Request request) {
                           super.onBefore(request);
                           //mHUDUtil.showHUD();
                       }

                       @Override
                       public BuildingListVo parseNetworkResponse(Response response) throws Exception {
                           return new Gson().fromJson(response.body().string(), getType());
                       }

                       @Override
                       public void onError(Call call, Exception e) {
                           if (pullToRefreshRecyclerView != null && mHUDUtil != null && multiStateView != null) {
                               pullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                               mHUDUtil.hidden();
                               multiStateView.setErrorTip(e.getLocalizedMessage());
                           }
                       }

                       @Override
                       public void onAfter() {
                           super.onAfter();
                       }

                       @Override
                       public void onResponse(BuildingListVo response) {
                           if (pullToRefreshRecyclerView != null) {
                               pullToRefreshRecyclerView.onRefreshComplete();
                           }
                           if (mHUDUtil != null) {
                               mHUDUtil.hidden();
                           }

                           mBuildingListVo = response;
                           if (mBuildingListVo != null) {
                               List<Building> temps = mBuildingListVo.getListob();
                               if (temps != null && temps.size() != 0) {
                                   if (currentPage == 1) {
                                       items.clear();
                                   }
                                   items.addAll(temps);
                                   if (mAdapter != null) {
                                       mAdapter.notifyDataSetChanged();
                                   }
                               }else{
                                   if (multiStateView != null) {
                                       multiStateView.setEmptyTip("无建筑信息");
                                   }
                               }


                               if (pullToRefreshRecyclerView != null) {
                                   if (mBuildingListVo.isHasNextPage()) {
                                       currentPage++;
                                       pullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
                                   } else {
                                       pullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                                   }
                               }
                           } else {
                               if (pullToRefreshRecyclerView != null) {
                                   pullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                               }
                           }
                       }
                   });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance()
                   .cancelTag(String.format(Urls.GET_BUILDING_LIST, mSharedPreferencesHelper.getRayEyeUrl()));
    }
}
